﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Text.RegularExpressions;

namespace BLL
{
    public class EmailService
    {
        private const string GYM_EMAIL_ADDRESS = "sadnamtagym@gmail.com";
        private const string GYM_EMAIL_PASS = "gymsadna";
        private const string SMTP = "smtp.gmail.com";

        public static bool SendEmail(string i_Subject, string i_Body, params string[] i_MailTo)
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(GYM_EMAIL_ADDRESS, string.Join(",", i_MailTo));
            message.Subject = i_Subject;
            message.Body = i_Body;

            SmtpClient smtp = new SmtpClient(SMTP, 25);
            smtp.EnableSsl = true;
            smtp.Timeout = 10000;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(GYM_EMAIL_ADDRESS, GYM_EMAIL_PASS);
            smtp.Send(message);
            return true;
        }

        public static bool SendEmailBcc(string i_Subject, string i_Body, params string[] i_BccAddresses)
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(GYM_EMAIL_ADDRESS, GYM_EMAIL_ADDRESS);
            message.Subject = i_Subject;
            message.Body = i_Body;
            foreach (string bcc in i_BccAddresses)
            {
                if (IsValidEmail(bcc))
                {
                    message.Bcc.Add(new MailAddress(bcc));
                }
            }

            SmtpClient smtp = new SmtpClient(SMTP, 25);
            smtp.EnableSsl = true;
            smtp.Timeout = 60000;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(GYM_EMAIL_ADDRESS, GYM_EMAIL_PASS);
            smtp.Send(message);
            return true;
        }

        public static bool IsValidEmail(string email)
        {
            Regex rx = new Regex(
            @"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
            return rx.IsMatch(email);
        }
    }
}
